﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.UI;

namespace AresCustomYacht
{
    public class Global : System.Web.HttpApplication
    {
        readonly BL _bl = new BL();
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            
            //LoadLookup("Boats");
            LoadLookup("Reports");
            LoadLookup("ReportDetails");
            AddToCache("Boats");


            ScriptManager.ScriptResourceMapping.AddDefinition("MicrosoftAjaxCore.js", new ScriptResourceDefinition
            {
                ResourceName = "MicrosoftAjaxCore.js",
                CdnPath = "http://ajax.aspnetcdn.com/ajax/act/40412/MicrosoftAjaxCore.js",
                CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/act/40412/MicrosoftAjaxCore.debug.js"
            });
        }

        private void AddToCache(string key)
        {
            //var callback = new CacheItemRemovedCallback(OnRemove);
            switch (key)
            {
                case "Boats":
                    //Context.Cache.Insert("Boats", _bl.GetBoats(), null, Cache.NoAbsoluteExpiration,
                    //            TimeSpan.Zero, CacheItemPriority.Default, callback);

                    Context.Cache.Insert("Boats",_bl.GetBoats());
                    break;
            }
           
        }

        public  void OnRemove(string key, object cacheItem, CacheItemRemovedReason reason)
        {
            AddToCache(key);
        }


        private void LoadLookup(string lookup)
        {
            switch (lookup.ToLower())
            {
                case "boats":
                    Application["Boats"] = _bl.GetBoats();
                    break;
                case "division":
                    break;
                case "trade":
                    break;
                case "reports":
                    Application["Reports"] = _bl.GetReports();
                    break;
                case "reportdetails":
                    Application["ReportDetails"] = _bl.GetReportDetails();
                    break;

                    default:
                    throw new Exception("No code to load table: " + lookup);

            }
        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError().GetBaseException();

            if (ex.Message.Contains("File does not")) return;

            //var mail = new onSoftMail();
            string technicalMsg = "";
            ConcatenateError(ex, ref technicalMsg);
            technicalMsg = Server.HtmlEncode(technicalMsg);
            //mail.SendMeMail(
            //    string.Format(
            //        "{0} <br /> Stack Trace:{1} <br /> Source:{2} <br /> Request.UserAgent:{3} <br /> Request.Headers.Keys:{4} <br /> Request.InputStream:{5} <br /> Request.RawUrl:{6} <br />  Request.UrlReferrer.AbsoluteUri{7}",
            //        technicalMsg, ex.StackTrace, ex.Source, Request.UserAgent, string.Join(",", Request.Headers.AllKeys),
            //        Request.InputStream, Request.RawUrl, Request.UrlReferrer.AbsoluteUri), "Exception in Unit Price");
            Response.Redirect("http://aresmarine.com/P-Exception.aspx?k=Message=" + ex.Message + "&TechMsg=" + technicalMsg);
        }

        private static void ConcatenateError(Exception ex, ref string exceptionMessage)
        //refactor with recursion to get all inner exceptions
        {
            if (ex != null)
                exceptionMessage += ex.Message + "\n";
            if (ex.InnerException != null)
                ConcatenateError(ex.InnerException, ref exceptionMessage);
        }

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.

        }

    }
}
